package com.amigo.online.provider.user.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import net.coobird.thumbnailator.Thumbnails;

/**
 * 图片处理工具
 *
 * @author Administrator
 */

@Component
public class ImgHandleUtil {

    private static Logger logger = Logger.getLogger(ImgHandleUtil.class);

    /**
     * 图片压缩
     *
     * @param file
     * @param width
     * @param height
     * @param tempFile
     */
    public static ByteArrayInputStream compressionImg(MultipartFile file, int width, int height) {
        ByteArrayOutputStream outputStream = null;
        try {
            InputStream inputStream = file.getInputStream();
            outputStream = new ByteArrayOutputStream();
            Thumbnails.of(inputStream)
                    .size(width, height)
                    .outputQuality(1)
                    .outputFormat("jpg")
                    .toOutputStream(outputStream);
        } catch (IOException e) {
            logger.error("图片压缩失败:");
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(outputStream.toByteArray());
        return bais;
    }

    public static ByteArrayInputStream compressionImgByUrl(String sourceUrl, int width, int height) {
        ByteArrayOutputStream outputStream = null;
        try {
            URL url = new URL(sourceUrl);
            outputStream = new ByteArrayOutputStream();
            Thumbnails.of(url)
                    .size(width, height)
                    .outputQuality(1)
                    .outputFormat("jpg")
                    .toOutputStream(outputStream);
        } catch (IOException e) {
            logger.error("图片压缩失败:");
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(outputStream.toByteArray());
        return bais;
    }

    public static ByteArrayOutputStream compressionImgByUrlToInputStream(byte[] source, int width, int height) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            InputStream inputStream = new ByteArrayInputStream(source);
            Thumbnails.of(inputStream)
                    .size(width, height)
                    .outputQuality(1)
                    .outputFormat("jpg")
                    .toOutputStream(outputStream);
        } catch (IOException e) {
            logger.error("图片压缩失败:" + e);
        }
        return outputStream;
    }


}
